package com.cuit.freshmanMS.controller;

import com.cuit.freshmanMS.service.ExcelService;
import com.cuit.freshmanMS.util.FileUtils;
import com.cuit.freshmanMS.util.result.CommonResult;
import com.cuit.freshmanMS.util.result.ResultCode;
import com.cuit.freshmanMS.util.result.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {
    @Autowired
    public ExcelService excelService;

    /**
     * 导入xlsx文件到数据库
     * @param file
     * @return
     */
    @PostMapping("/import")
    public CommonResult<Boolean> importFile(@RequestBody MultipartFile file) throws IOException {
        if (file == null){
            return ResultUtil.fail(ResultCode.PARAM_IS_BLANK);
        }
        return excelService.importFile(file);
    }


    /**
     * 导出数据库学生文件到template.xlsx文件并通过浏览器下载
     *
     * 如果返回CommonResult类型，报错：Servlet.service() for servlet [dispatcherServlet] in
     * context with path [] threw exception [Request processing failed; nested exception
     * is org.springframework.http.converter.HttpMessageNotWritableException: No converter
     * for [class com.cuit.freshmanMS.util.result.CommonResult] with preset Content-Type
     * 'application/x-msdownload;charset=UTF-8'] with root cause
     *
     * 错误原因：Spring Boot找不到适合将CommonResult类转换为application/x-msdownload;charset=UTF-8格式的消息转换器
     *
     * 在service层和调用的FileUtils类的方法都设置了返回CommonResult类型，在controller层直接返回String类型，可以跑通
     *
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/download")
    public String downloadFile(HttpServletResponse response) throws IOException {
        //刷新静态文件的数据
        excelService.exportFile();

        String fileName = "template.xlsx";
        //下载静态文件
        FileUtils.downloadFile(response, fileName);
        return "success";
    }

    /**
     * 选择sids导出
     * @param response
     * @param sids
     * @return
     * @throws IOException
     */
    @PostMapping("/selectDownload")
    public String selectDownloadFile(HttpServletResponse response, @RequestBody List<String> sids) throws IOException {
        excelService.selectExportFile(sids);

        String fileName = "template.xlsx";
        FileUtils.downloadFile(response, fileName);
        return "success";
    }
}
